﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using IIControls.IAControl;
using IIControls.Source;
using System.Data;
using Communicate;
using System.Web.Script.Serialization;
using BusTransfer;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Threading;
using ModbusCommunicate;
using System.Threading.Tasks;

namespace ControlTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            msgreg();
             dt = new DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0,5);
            dt.Tick += Dt_Tick;
            //ModbusInit();
        }
        /*
         控件使用方法：
         1、new ValveControl(new Valve)  进行添加控件
         2、使用msgreg()中提供的方法注册消息
         3、控件移除时需要调用ValveControl.UnReg();
             */

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            

            ValveControl S = addSunValve(new Point(300, 160), (int)ValveControl.ValveState.OPEN);
            S.SetValveCallBack(ValveControl.ValveState.STATUE, false);
            ValveControl a1 = addSunValve(new Point(600, 160), (int)ValveControl.ValveState.CLOSE);
            a1.SetValveCallBack(ValveControl.ValveState.STATUE, true);
            ValveControl a2 =addSunValve(new Point(900, 160),(int) ValveControl.ValveState.OPEN );
            a2.SetValveCallBack(ValveControl.ValveState.VOLTAGE, 3.44);
            ValveControl a3 = addSunValve(new Point(1200, 160),(int) ValveControl.ValveState.CLOSE  );
           
            a3.SetValveCallBack(ValveControl.ValveState.ERROR);
            string a = S.SunValveNo;
            //S.SetValveCallBack(ValveControl.ValveState.STATUE, true);
            //S.SetValveCallBack(ValveControl.ValveState.OPEN, 1);
            a1.ValveId = "08128912";
            a1.ValveDetail = "阀门2";
            a1.SetIdToolTip();
            a1.Valveinit.GPRSNumber = "20018008";
            a1.Valveinit.CoorNumber = 8.ToString();
            a2.ValveId = "08128313";
            a2.ValveDetail = "阀门3";
            a2.SetIdToolTip();
            a2.Valveinit.GPRSNumber = "20018008";
            a2.Valveinit.CoorNumber = 8.ToString();
            a3.ValveId = "08128322";
            a3.SetIdToolTip();
            a3.ValveDetail = "阀门2";
            a3.Valveinit.GPRSNumber = "20018008";
            a3.Valveinit.CoorNumber = 8.ToString();
            S.ValveId = "08128323";
            S.SetIdToolTip();
            S.ValveDetail = "阀门3";
            S.Valveinit.GPRSNumber = "20018008";
            S.Valveinit.CoorNumber = 8.ToString();

            sourceC = addsourcecontrol(new Point(60, 460));

            //初始化串口发送，通过协调器发送，SPRD：串口返回数据委托
            APBSP = new AgreePrivateBySerialPort(new AgreePrivateBySerialPort.ReturnRes(SPRD), 0);
            if (APBSP.SerialPortInit(9600, "COM1", 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None) == false)
                MessageBox.Show("初始化错误");

            //初始化串口发送，通过GPRS发送JSON格式，SPRD：串口返回数据委托
            APB2GPRS = new AgreePrivateBySerialPort2GPRS(new AgreePrivateBySerialPort.ReturnRes(SPRD));
            if (APB2GPRS.SerialPortInit(9600, "COM3", 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None) == false)
                MessageBox.Show("初始化错误");
            //通过网络发送，发送JSON格式
            TCPINIT();
            addSunValvebyvalve(new Point(600, 360), (int)ValveControl.ValveState.CLOSE);

        
        }

        #region modbus相关
        void ModbusInit()
        {
            ModbusCommunicate.ModbusReg REG = new ModbusReg() { devicetype = 3, phone = "13912345678", reg_id = "10040001", user_key = "modbus" };
            ModbusCommunicate.SendByTcp.InitData SI = new ModbusCommunicate.SendByTcp.InitData();
            SI.MR = REG;
            SI.ip = "10.60.132.195";
            SI.port = 5006;
            SI.heartbeat = new byte[] { 0x2b };
            SI.heartbeatfreq = 30;
            string reg = jserial.Serialize(SI.MR);
            SI.register = System.Text.Encoding.Default.GetBytes(reg);
            MBBT = new ModBusByTcp(SI);
            ModBusReg(REG.reg_id );
            MBBT.AsyncTcpConnect();
        }

        /// <summary>
        /// modbus注册回调方法
        /// </summary>
        void ModBusReg(string gprscode)
        {
            BusTransfer.MsgTransfer.Instance.Register<ModbusCommunicate.SendByTcp.ModbusEvent>(this, gprscode + "@modbus", ModbusEvent);
            BusTransfer.MsgTransfer.Instance.Register<byte[]>(this, gprscode + "@modbus", ModbusData);
        }

        /// <summary>
        /// 注销注册事件
        /// </summary>
        void ModBusUnreg( string gprscode)
        {
            BusTransfer.MsgTransfer.Instance.Unregister<ModbusCommunicate.SendByTcp.ModbusEvent>(this, gprscode + "@modbus", ModbusEvent);
            BusTransfer.MsgTransfer.Instance.Unregister<byte[]>(this, gprscode + "@modbus", ModbusData);
        }

        /// <summary>
        /// modbus事件处理
        /// </summary>
        /// <param name="ID"></param>
        private void ModbusEvent(ModbusCommunicate.SendByTcp.ModbusEvent e)
        {
            Dispatcher.Invoke(new Action(() => MBEvent(e)));
        }

        /// <summary>
        /// modbus事件
        /// </summary>
        /// <param name="e"></param>
        void MBEvent(ModbusCommunicate.SendByTcp.ModbusEvent e)
        {
            switch (e.events)
            {
                case ModbusCommunicate.SendByTcp.MBEvent.TcpConnected:
                    MessageBox.Show(e.Detail);
                    break;
                case ModbusCommunicate.SendByTcp.MBEvent.TcpConnectFail:
                    ModBusUnreg(e.MR.reg_id);  //服务器连接失败取消消息传递
                    MessageBox.Show(e.Detail);
                    break;
                case ModbusCommunicate.SendByTcp.MBEvent.TcpSendfail:
                    MessageBox.Show(e.Detail);
                    break;
            }
        }

        class tt
        {
            public string names { get; set; }

            public object values { get; set; }
        }

        /// <summary>
        /// modbus数据解析完成
        /// </summary>
        /// <param name="data"></param>
        private void ModbusData(byte[] data)
        {
            string MBData = System.Text.Encoding.Default.GetString(data);
            Dictionary<string, object> dic_data = jserial .Deserialize<Dictionary<string, object>>(MBData);
            if (dic_data.ContainsKey("reg_id"))
                MessageBox.Show("服务器注册成功");
        } 
        #endregion

        private void SPRD(AgreePrivateBySerialPort.ReceiveStruct RS)
        {
            string res = RS.AnalyResult;
            byte[] data = RS.ReceiveData;
            this.Dispatcher.Invoke(new Action(() => Datas(data, res)));
        }

        PumpControl sourceC;
        PumpControl addsourcecontrol(Point p)
        {
            ControlType CT = new ControlType() { Name="泵房控制器",Number= "09003", GPRSNumber= "20024046", CoorNumber="9"};
            PumpControl SC = new PumpControl(CT  );
            ROOT.Children.Add(SC);
            Canvas.SetLeft(SC, p.X + 300);
            Canvas.SetTop(SC, 300);
            return SC;
        }

        DataTable RECORD()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("时间");
            dt.Columns.Add("操作");
            for (int i = 0; i < 100; i++)
            {
                DataRow DR = dt.NewRow();
                DR[0] = DateTime.Now.ToString();
                if (i % 2 == 0)
                    DR[1] = "开";
                else
                    DR[1] = "关";
                dt.Rows.Add(DR);
            }
            return dt;
        }

        ValveControl addSunValvebyvalve(Point p, int valvestate)
        {
            Valve V = new Valve() { Number = "08637", Type = 3, Name = "valv生成", State = valvestate
            , CoorNumber="8",GPRSNumber="20018008"};
            //ValveControl.CmdClickDelegate SCCD = new ValveControl.CmdClickDelegate(SunControls);
            ValveControl SC = new ValveControl();
            SC.Valveinit = V;
            SC.Width = 230;
            SC.Height = 130;
            ROOT.Children.Add(SC);
            Canvas.SetLeft(SC, p.X + 300);
            Canvas.SetTop(SC, 200);
            SC.Valve_Init();
            DataTable dt = new DataTable();
            dt.Columns.Add("时间");
            dt.Columns.Add("操作");
            dt.Columns.Add("时长");
            for (int i = 0; i < 100; i++)
            {
                DataRow DR = dt.NewRow();
                DR[0] = DateTime.Now.ToString();
                if (i % 2 == 0)
                    DR[1] = "开";
                else
                    DR[1] = "关";
                DR[2] = 0;
                dt.Rows.Add(DR);
            }
            SC.HisTory = dt;
            return SC;
        }

        ValveControl addSunValve(Point p, int valvestate )
        {
            Valve V = new Valve() { Number= "65535", Type=3, Name="默认东西",State=valvestate ,GPRSNumber="20018008"};
            //ValveControl.CmdClickDelegate SCCD = new ValveControl.CmdClickDelegate(SunControls);
            ValveControl SC = new ValveControl(V);
            SC.Width = 230 ;
            SC.Height = 130 ;
            ROOT.Children.Add(SC);
            Canvas.SetLeft(SC, p.X+ 300);
            Canvas.SetTop(SC, 100);
            SC.Valve_Init();
            DataTable dt = new DataTable();
            dt.Columns.Add("时间");
            dt.Columns.Add("操作");
            dt.Columns.Add("时长");
            for(int i=0;i<100;i++)
            {
                DataRow DR = dt.NewRow();
                DR[0] = DateTime.Now.ToString();
                if (i % 2 == 0)
                    DR[1] = "开";
                else
                    DR[1] = "关";
                DR[2] = 0;
                dt.Rows.Add(DR);
            }
            SC.HisTory = dt;
            return SC;
        }

        ValveControl addSunValves(Point p, ValveControl.ValveState sv, object o = null)
        {
            //ValveControl.CmdClickDelegate SCCD = new ValveControl.CmdClickDelegate(SunControls);
            ValveControl SC = new ValveControl();
            SC.Width = 160;
            SC.Height = 90;
            SC.SetValveCallBack( sv, 1 );
            ROOT.Children.Add(SC);
            Canvas.SetLeft(SC, p.X + 300);
            Canvas.SetTop(SC, 300);
            //SC.Valve_Init();
            DataTable dt = new DataTable();
            dt.Columns.Add("时间");
            dt.Columns.Add("操作");
            dt.Columns.Add("时长");
            for (int i = 0; i < 100; i++)
            {
                DataRow DR = dt.NewRow();
                DR[0] = DateTime.Now.ToString();
                if (i % 2 == 0)
                    DR[1] = "开";
                else
                    DR[1] = "关";
                DR[2] = 0;
                dt.Rows.Add(DR);
            }
            SC.HisTory = dt;
            return SC;
        }

        void SourceClick(PumpControl PumpClick)
        {
           MessageBox.Show( PumpClick.PumpOrder.ToString()+"@@@"+PumpClick.ClickButton.ToString());
            DateTime DT = PumpClick.GetClickTime(PumpControl.PumpCMD.Channel1Open);
        }



        void SunControls(ValveControl valve)
        {
            // MessageBox.Show(valve.OperType .ToString()+"@@@"+ valve.CT .ToString());
            //    TaskMsg tm = new TaskMsg();
            //    tm.CmdType = (int)valve.CT;
            //    tm.DeviceAllMsg = valve;
            //    tm.OperTime = DateTime.Now;
            //    APBSP.ADDTasks(tm);
            //    APB.ADDTasks(tm);
        }
        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //Se.ValveStatus =(SEControl.STATUS) comboBox.SelectedItem;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Pump1Open);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Pump1Close);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Pump2Open);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Pump2Close);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.FrontPress, 4.5222);
            //sourceC.SetPumpCallBack(PumpControl.PumpCallBack.CheckStatue, PumpControl.PumpControlStatue.Pump1 | PumpControl.PumpControlStatue.Pump2 | PumpControl.PumpControlStatue.Channel1 | PumpControl.PumpControlStatue.Channel2 | PumpControl.PumpControlStatue.Channel3);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.PumpInit);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Channel1Open);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Channel1Close);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Channel2Open);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Channel2Close);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Channel3Open);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.Channel3Close);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.ReadRecord, RECORD());
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.ClearRecord);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.ReadTime, DateTime.Now);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.SyncTime);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.CommError);

            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.BackPress, 1.23456);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.FrontPress, 0.23456);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.PumpFlow, 150.6);
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.PumpVoltage, new double[] { 380.123, 380.456, 380.567 });
            //sourceC.SetPumpCallBack(SourceControl.PumpCallBack.PumpElectric, new double[] { 110.258, 0.259, 25366.123 });
        }

        AgreePrivateBySerialPort APBSP;

        void ReceiveData(AgreePrivateBySerialPort .ReceiveStruct SR)
        {
            string res = SR.AnalyResult;
            byte[] data = SR.ReceiveData;
            textBlock.Text   += res + "\r\n";
        }
        
        AgreePrivateByTcp APB;

        private void TCPINIT()
        {
           Communicate.  SendByTcp.InitData Data = new Communicate.SendByTcp.InitData();
            Data.ip = "123.57.151.4";
            Data.port = 5005;
            JSON_REG REG = new JSON_REG();
            //REG.gprs_code = "10018100";
            REG.gprs_code = "10024100";
            REG.phone_code = "13912345678";
            REG.user_key = "hahaha";
            JavaScriptSerializer JS = new JavaScriptSerializer();
            Data.register = System.Text.Encoding.Default.GetBytes(JS.Serialize(REG));
            Data.heartbeat = new byte[] { 0x2b };
            //心跳包发送频率，0不发送，>0单位秒
            Data.heartbeatfreq = 0;
            //TCPReceiveData：网络返回数据
            APB = new AgreePrivateByTcp(Data,new AgreePrivateByTcp.TCPReceiveData (TCPReceiveData));
              if(!  APB.SocketStart())
                    MessageBox.Show("连接失败");
              else
                MessageBox.Show("连接成功");
        }

        /// <summary>
        /// TCP收到数据,返回的数据保证都是正确的
        /// </summary>
        /// <param name="data"></param>
        /// <param name="data2string"></param>
        public  void TCPReceiveData(byte[] data, string data2string)
        {
            this.Dispatcher.Invoke(new Action(() => Datas(data, data2string)));
        }
        JavaScriptSerializer jserial = new JavaScriptSerializer();

        /// <summary>
        /// 收到的数据进行显示
        /// </summary>
        /// <param name="data">收到的数组</param>
        /// <param name="res">数组解析成字符串</param>
        private void Datas(byte[] data, string res)
        {

            textBlock.Text += res + "\r\n";
            //ReceiveDataAnaly(data, res);
        }

        private void ReceiveDataAnaly(byte[] data ,string res)
        {
            Dictionary<string, object> recData = jserial.Deserialize<Dictionary<string, object>>(res);
            if (recData == null)
                return;
            int devicecode = Convert.ToInt32(recData["device_type"]);
            switch (devicecode)
            {
                case 1:
                    switch (Convert.ToInt32(recData["device_cmd"]))
                    {
                        case 49:  //阀门1开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.OPEN, null }, "v_" + (string)recData["device_code"] + "1");
                            break;
                        case 50:  //阀门1关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.CLOSE, null }, "v_" + (string)recData["device_code"] + "1");
                            break;
                        case 51:  //阀门2开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.OPEN, null }, "v_" + (string)recData["device_code"] + "2");
                            break;
                        case 52:  //阀门2关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.CLOSE, null }, "v_" + (string)recData["device_code"] + "2");
                            break;
                        case 53:  //阀门3开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.OPEN, null }, "v_" + (string)recData["device_code"] + "3");
                            break;
                        case 54:  //阀门3关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.CLOSE, null }, "v_" + (string)recData["device_code"] + "3");
                            break;
                        case 55:  //阀门4开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.OPEN, null }, "v_" + (string)recData["device_code"] + "4");
                            break;
                        case 56:  //阀门4关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.CLOSE, null }, "v_" + (string)recData["device_code"] + "4");
                            break;
                        case 57:  //状态
                            string[] statues = (string[])((System.Collections.ArrayList)recData["list"]).ToArray(typeof(string));
                            for (int i = 0; i < statues.Length; i++)
                            {
                                BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.STATUE, Convert.ToInt32(statues[i]) > 0 ? true : false }, "v_" + (string)recData["device_code"] + (i + 1).ToString());
                            }
                            break;

                        case 58:  //电压                         
                        case 62://58,62两种条件处理方法一致
                            double vol = Convert.ToDouble(recData["retdata"]);
                            for (int i = 0; i < 4; i++)
                            {
                                BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.VOLTAGE, vol }, "v_" + (string)recData["device_code"] + (i + 1).ToString());
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case 2:
                    break;
                case 3:
                    switch (Convert.ToInt32(recData["device_cmd"]))
                    {
                        case 1:  //读信息
                            break;
                        case 2: //初始化
                            for (int i = 0; i < 4; i++)
                            {
                                BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.INIT, null }, "v_" + (string)recData["device_code"] + (i + 1).ToString());
                            }
                            break;

                    }
                    break;
                case 4:
                    switch (Convert.ToInt32(recData["device_cmd"]))
                    {
                        case 1:  //通道1开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Channel1Open, null }, "v_" + (string)recData["device_code"]);
                            break;
                        case 2:  //通道1关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Channel1Close, null }, "v_" + (string)recData["device_code"]);
                            break;
                        case 3:  //通道2开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Channel2Open, null }, "v_" + (string)recData["device_code"]);
                            break;
                        case 4:   //通道2关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Channel2Close, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 5:  //通道3开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Channel3Open, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 6:  //通道3关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Channel3Close, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 7:  //闸刀开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.ValveOpen, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 8:  //闸刀关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.ValveClose, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 9: //原井开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Pump1Open, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 10:  //原井关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Pump1Close, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 11:  //增压泵开
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Pump2Open, null }, "v_" + (string)recData["device_code"]);
                            break;

                        case 12:  //增压泵关
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Pump2Close, null }, "v_" + (string)recData["device_code"]);
                            break;
                        case 13:  //检测状态
                            break;

                        case 14:  //检测压力
                            break;

                        case 16:  //同步日期
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.SyncTime, null }, "v_" + (string)recData["device_code"]);
                            break;
                        case 17:  //读取报警信息
                            break;
                        case 18: //清除报警信息
                            break;
                        case 21:  //读取日期
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.Pump2Close, Convert.ToDateTime((string)recData["retdata"]) }, "v_" + (string)recData["device_code"]);
                            break;
                        case 22: //测量电压
                            break;
                        case 23: //报警自动回发
                            break;

                    }
                    break;
                case 5:
                    break;
                case 6:
                    break;
                case 10:
                    switch (Convert.ToInt32(recData["device_cmd"]))
                    {
                        case 1:
                            break;
                        case 11:  //通信失败
                            for (int i = 0; i < 4; i++)
                            {
                                BusTransfer.MsgTransfer.Instance.Send(new object[] { ValveControl.ValveState.ERROR, null }, "v_" + (string)recData["retdata"] + (i + 1).ToString());
                            }
                            BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.CommError, null }, "v_" + (string)recData["retdata"]);
                            break;
                    }
                    break;
                default:
                    break;
            }
        }



        private void button6_Click(object sender, RoutedEventArgs e)
        {

            APB.AP.sendImmediatelyTask("20018008", 10, 15, new int[] { 8 }, null);
            APBSP  .AP. sendImmediatelyTask("", 10, 15, new int[] { 8 }, null);
            APB2GPRS.AP.sendImmediatelyTask("20018008", 10, 15, new int[] { 8 }, null);
        }

        AgreePrivateBySerialPort2GPRS APB2GPRS;


        #region 消息件
      void msgunreg()
        {
            //增加操作
            MsgTransfer.Instance.Unregister <TaskMsg>(this, "v_addtask", AddTask);
            //减少操作
            MsgTransfer.Instance.Unregister<TaskMsg>(this, "v_deltask", DelTask);
            //进行配置田间控制器
            MsgTransfer.Instance.Unregister<NotificationMessage<ValveControl>>(this, Config);
            //进行泵房控制器配置
            MsgTransfer.Instance.Unregister <NotificationMessage<PumpControl>>(this, pumpconfig);

        }

        void msgreg()
        {
            //增加操作
            MsgTransfer.Instance.Register<TaskMsg>(this,"v_addtask", AddTask);
            //减少操作
            MsgTransfer.Instance.Register<TaskMsg>(this,"v_deltask", DelTask);
            //进行配置
            MsgTransfer.Instance.Register<NotificationMessage<ValveControl>>(this,Config);
            //进行泵房控制器配置
            MsgTransfer.Instance.Register<NotificationMessage<PumpControl>>(this, pumpconfig);
        }

        private void pumpconfig(NotificationMessage<PumpControl> obj)
        {
            Dispatcher.Invoke(() =>
            {
                PumpControl.ClickType CT = (PumpControl.ClickType)obj.Sender ;
                switch (CT )
                {
                    case PumpControl.ClickType.ReadHistory:
                        DataTable dt = new DataTable();
                        dt.Columns.Add("草包1");
                        dt.Columns.Add("草包2");
                        dt.Columns.Add("草包3");
                        DataRow dr = dt.NewRow();
                        dr[0] = 1;
                        dr[1] = DateTime.Now;
                        dr[2] = DateTime.Now.AddSeconds(100);
                        dt.Rows.Add(dr);
                        BusTransfer.MsgTransfer.Instance.Send(new object[] { PumpControl.PumpCallBack.ReadRecord , dt }, "v_" +obj.Content.Pumpinits.GPRSNumber+ obj.Content.PumpId );
                        break;
                    case PumpControl.ClickType.Save:
                        break;
                }
            });
        }

        private void Config(NotificationMessage<ValveControl> obj)
        {
            Dispatcher.Invoke(() => { ChangeConfig(obj); });
        }


        /// <summary>
        /// 用于设置控件属性
        /// </summary>
        /// <param name="obj"></param>
        void ChangeConfig(NotificationMessage<ValveControl> obj)
        {
                ValveControl v = (ValveControl)obj.Content;
                ValveControl.ClickType CT = (ValveControl.ClickType)obj.Sender ;
                switch(CT )
                {
                    case ValveControl.ClickType.ValveReadHistory :  //读取历史
                    DataTable dt = new DataTable();
                    dt.Columns.Add("草包1");
                    dt.Columns.Add("草包2");
                    dt.Columns.Add("草包3");
                    DataRow dr = dt.NewRow();
                    dr[0] = 1;
                    dr[1] = DateTime.Now;
                    dr[2] = DateTime.Now.AddSeconds(100);
                    dt.Rows.Add(dr);
                    v.HisTory = dt;                  //数据库中读取操作记录放入v.HisTory用于显示
                        break;
                    case ValveControl.ClickType.ValveSave :    //在数据库张保存配置，编号
                        
                        break;
                }
         }
        


        /// <summary>
        /// 添加任务队列
        /// </summary>
        /// <param name="tm"></param>
        private void AddTask(TaskMsg tm)
        {
            APB.ADDTasks(tm);
            APB2GPRS.ADDTasks(tm);
            APBSP.ADDTasks(tm);
            dt.Stop();
            dt.Start();
        }

        /// <summary>
        /// 移除任务
        /// </summary>
        /// <param name="tm"></param>
        private void DelTask(TaskMsg tm)
        {
            APB.DELTasks(tm);
            APB2GPRS.DELTasks(tm);
            APBSP .DELTasks(tm);
        }

        /// <summary>
        /// 开始任务
        /// </summary>
        private void StartTask()
        {
            APB.TasksStart();
            APB2GPRS.TasksStart();
            APBSP.TasksStart();
        }

        DispatcherTimer dt;
        /// <summary>
        /// 任务计时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Dt_Tick(object sender, EventArgs e)
        {
            dt.Stop();
            StartTask();
        }


        #endregion
        ModBusByTcp MBBT ;
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ModbusSend MS = new ModbusSend() {  device_cmd=6, device_id=1,  device_WriteData = new byte[] { 1 }, device_startreg =0x1000, socket_id="20040001", IsLowBitFirst = true };
            MBBT.ADDTask(MS);
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ModbusSend MS = new ModbusSend() { device_cmd = 3, device_id = 1,  device_startreg = 0x1000, device_WriteData=new byte[] { 5 }, socket_id = "20040001" , IsLowBitFirst=true };
            MBBT.ADDTask(MS);
        }
    }
}
